package mobidever.mygodutch.database.base;

import java.util.ArrayList;
import java.util.List;

import mobidever.mygodutch.database.base.SQLiteHelper.SQLiteDataTable;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public abstract class SQLiteDALBase implements SQLiteDataTable
{
	private Context mContext;
	private SQLiteDatabase mDatabase;

	public SQLiteDALBase(Context pContext)
	{
		mContext = pContext;
	}

	public Context getContext()
	{
		return mContext;
	}

	public SQLiteDatabase getDatabase()
	{
		if (mDatabase == null)
		{
			mDatabase = SQLiteHelper.getSqLiteHelper(mContext).getWritableDatabase();
		}
		return mDatabase;
	}

	public void beginTransaction()
	{
		mDatabase.beginTransaction();
	}

	public void setTransactionSuccessful()
	{
		mDatabase.setTransactionSuccessful();
	}

	public void endTransaction()
	{
		mDatabase.endTransaction();
	}

	public int getCount()
	{
		String[] NameAndPK = getTableNameAndPK();

		Cursor _Cursor = ExecSQL("select " + NameAndPK[1] + " from "
				+ NameAndPK[0] + "where 1=1 ");
		int _count = _Cursor.getCount();
		_Cursor.close();
		return _count;
	}

	public int getCount(String pTableName, String pPK, String pCondition)
	{
		String[] NameAndPK = getTableNameAndPK();

		Cursor _Cursor = ExecSQL("select " + pTableName + " from " + pPK
				+ "where 1=1 " + pCondition);
		int _count = _Cursor.getCount();
		_Cursor.close();
		return _count;
	}

	public Boolean delete(String pTableName, String pCondition)
	{

		return getDatabase().delete(pTableName, "1=1" + pCondition, null) >= 1;
	}

	public List getList(String pCondition)
	{
		Cursor _Cursor = ExecSQL(pCondition);
		return CursorToList(_Cursor);
	}

	public List CursorToList(Cursor pCursor)
	{
		ArrayList _ArrayList = new ArrayList();
		while (pCursor.moveToNext())
		{
			Object _Object = findModel(pCursor);
			_ArrayList.add(_Object);
		}
		pCursor.close();
		return _ArrayList;
	}

	public Cursor ExecSQL(String pSql)
	{
		return getDatabase().rawQuery(pSql, null);
	}

	protected abstract String[] getTableNameAndPK();

	protected abstract Object findModel(Cursor pCursor);
}
